package cn.xdf.demo01;

import cn.xdf.entity.Goods;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class Demo03_set查询 {

    private HttpSolrServer solrServer=new HttpSolrServer("http://localhost:9090/solr/Goods");



    @Test
    public void test01() throws Exception {
        //构建查询条件
        SolrQuery solrQuery=new SolrQuery();

        //构建条件
        solrQuery.set("q","title:小米笔记本");
        solrQuery.set("fq","price:[2000 TO 5000]");
        solrQuery.set("sort","price desc");
        solrQuery.set("start",1);
        solrQuery.set("rows",5);
        solrQuery.set("fl","id,name,title");
        //执行查询
        QueryResponse response = solrServer.query(solrQuery);
        //获取结果集
        List<Goods> goodsList = response.getBeans(Goods.class);
        for(Goods goods:goodsList){
            System.out.println(goods);

        }
    }


    @Test
    public void test02() throws Exception {
        //构建查询条件
        SolrQuery solrQuery=new SolrQuery();

        //构建条件
        solrQuery.set("q","title:小米笔记本");

        solrQuery.set("hl",true);
        solrQuery.set("hl.fl","name,title");
        solrQuery.set("hl.simple.pre","<font color='red'>");
        solrQuery.set("hl.simple.post","</font>");


        //执行查询
        QueryResponse response = solrServer.query(solrQuery);
        //获取结果集
        List<Goods> goodsList = response.getBeans(Goods.class);

        //高亮数据
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

        //遍历高亮数据
//        for(String docId : highlighting.keySet()){
//            //根据文档id获取这个文档的高亮数据
//            Map<String, List<String>> listMap = highlighting.get(docId);
//
//            List<String> name = listMap.get("name");
//            List<String> title = listMap.get("title");
//
//            if(name!=null){
//                System.out.println(name.get(0));
//            }
//
//            if(title!=null){
//                System.out.println(title.get(0));
//
//            }
//
//        }

        for(Goods goods:goodsList){
            Map<String, List<String>> docHigh = highlighting.get(goods.getId());

            List<String> nameList = docHigh.get("name");
            List<String> titleList = docHigh.get("title");

            if(nameList!=null){
                goods.setName(nameList.get(0));
            }

            if(titleList!=null){
                goods.setTitle(titleList.get(0));
            }

            System.out.println(goods);
        }
    }
}


